package com.net.model.base.fragment;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewbinding.ViewBinding;

import com.drug.lib.view.LoadingDialog;
import com.net.model.R;

public abstract class BaseVBDialogFragment<T extends ViewBinding> extends SupportDialogFragment {
    protected T mBinding;
    protected Context mContext;
    protected FragmentManager fragmentManager;
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mBinding = getViewBinding();
        return mBinding.getRoot();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFullScreen); //dialog全屏
        measureScreenSize();
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = this.getDialog().getWindow();
        //去掉dialog默认的padding
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.height = getWindowHeight();
        lp.width = getWindowWidth();
        //设置dialog的位置在底部
        lp.gravity = Gravity.CENTER;
        //设置dialog的动画
        lp.windowAnimations = R.style.BottomDialogAnimation;
        window.setAttributes(lp);
        window.setBackgroundDrawable(new ColorDrawable());
        getDialog().setCanceledOnTouchOutside(isCancelable());
        getDialog().setCancelable(isCancelable());
    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        fragmentManager = getChildFragmentManager();
        initialize();
        initData();
        requestNetwork();
        createLoadDialog();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mBinding = null;
    }

    /**
     * 获取加载布局文件
     */
    protected abstract T getViewBinding();

    public  boolean isCancelable(){
        return true;
    }

    protected int getWindowHeight() {
        return WindowManager.LayoutParams.WRAP_CONTENT;
    }

    protected int getWindowWidth() {
        return WindowManager.LayoutParams.WRAP_CONTENT;
    }


    /**
     * 初始化数据
     */
    protected abstract void initialize();

    protected abstract void initData();

    protected abstract void requestNetwork();

    LoadingDialog loadingDialog;

    public void createLoadDialog() {
        LoadingDialog.Builder builder = new LoadingDialog.Builder(getContext())
                .setMessage("加载中...")
                .setCancelOutside(true)
                .setCancelable(false);
        loadingDialog = builder.create();
    }

    /**
     * description: 加载动画消失
     *
     * @author: zhouhequan
     * @date: 2021/10/25 11:15
     * @return: void
     */

    public void dismissDialog() {
        if (loadingDialog.isShowing())
            loadingDialog.dismiss();
    }

    /**
     * description: 加载动画显示
     *
     * @author: zhouhequan
     * @date: 2021/10/25 11:16
     * @return: void
     */

    public void showLoading() {
        if (!loadingDialog.isShowing())
            loadingDialog.show();
    }

    private Handler handler;

    protected final Handler getHandler() {
        if (handler == null) {
            handler = new Handler(mContext.getMainLooper());
        }
        return handler;
    }

    int screenWidth;
    int screenHeight;

    private void measureScreenSize() {
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
    }

    protected int getScreenHeight() {
        return screenHeight;
    }

    protected int getScreenWidth() {
        return screenWidth;
    }


    /**
     * fragment中添加fragment（add方式）
     *
     * @param target Fragment
     * @param args   Bundle
     */
    protected void startFragment(Fragment target, @IdRes int res, Bundle args) {
        if (args != null)
            target.setArguments(args);
        fragmentManager.beginTransaction()
                .setReorderingAllowed(true)
                .add(res, target)
                .addToBackStack(target.getClass().getSimpleName())
                .commit();
    }

    /**
     * fragment中添加fragment（replace方式）
     *
     * @param target Fragment
     * @param args   Bundle
     */
    protected void replaceFragment(Fragment target, @IdRes int res, Bundle args) {
        target.setArguments(args);
        fragmentManager.beginTransaction()
                .setReorderingAllowed(true)
                .replace(res, target)
                .addToBackStack(target.getClass().getSimpleName())
                .commit();
    }

    /**
     * 清空当前栈所有fragment
     */
    private void clearFragmentStack() {
        int count = fragmentManager.getBackStackEntryCount();
        if (count > 0) {
            FragmentManager.BackStackEntry entry = fragmentManager.getBackStackEntryAt(0);
            fragmentManager.popBackStack(
                    entry.getName(),
                    FragmentManager.POP_BACK_STACK_INCLUSIVE
            );
        }
    }
}
